<template>
    <div id="app">
        <HeaderPage  :avatar="avatar" :nick_name="nick_name" :is_admin="isAdmin"></HeaderPage>
        <h5 class="page_title"><el-button link @click="goto_user_center"> &lt;返回</el-button> &nbsp;我的优惠券</h5>  
        <div class="filter_bar">
            <span class="filter_title">有效期</span>
            <el-select
            class="selector"
            @change="handleSelect"
            v-model="status"
            placeholder="优惠券状态">
                <el-option 
                v-for="item in status_options"
                :label="item.text"
                :value="item.id"
                :key="item.text">
                </el-option>
            </el-select>
       
            <span class="filter_title">优惠券类型</span>
            <el-select 
            class="selector"
            @change="handleSelect"
            v-model="coupon_check_type"
            placeholder="优惠券类型">
                <el-option 
                v-for="item in coupon_type_options"
                :key="item.text"
                :value="item.id"
                :label="item.text"
                ></el-option>
            </el-select>
        </div>
        
        <div class="empty_coupon" v-show="coupons.length===0">
            <span>还没有优惠券，分享给朋友，对方激活后可获取优惠券。</span>
            <el-button plain style="margin-left:65dvw" @click="copy_promotion_link">点击复制推广链接</el-button>
        </div>

       
       <el-scrollbar height="500px" class="scroll-container" ref="refScrollbar">
        <el-row v-if="coupons.length!=0&&status==1"><span class="rules_announce">代金券消耗不找零，一次最低消费一张</span></el-row>
        <el-row class="coupon_row">
            <el-col 
                v-for="(o, index) in coupons.length"
                :key="o"
                :span="6"
                :offset="1">
                <el-card v-if="status==1" class="coupon_card" :body-style="{ padding: '0px' }">
                    <div class="coupon_point"> {{coupons[index].coupon_points}}</div>
                    <div class="coupon_name">{{coupons[index].coupon_name}}</div>
                    <div class="coupon_expiration"><span style="display: block;">有效期至:</span>{{coupons[index].coupon_expiration}}</div>
                </el-card>

                <el-card v-else class="coupon_card" :body-style="{ padding: '0px' }">
                    <div class="invalid_coupon_point"> {{coupons[index].coupon_points}}</div>
                    <div class="coupon_name">{{coupons[index].coupon_name}}</div>
                    <div class="coupon_expiration"><span style="display: block;">过期时间:</span>{{coupons[index].coupon_expiration}}</div>
                
                </el-card>
            </el-col>
        </el-row>        
       </el-scrollbar>
        <FooterPage></FooterPage>
    </div>
</template>

<script>
 import HeaderPage from '@/components/HeaderPage.vue'
 import FooterPage from '@/components/FooterPage.vue'
 import axios from 'axios'
 import config from '../../spoken.config.json';
 import { ElNotification } from 'element-plus';

export default{
     name:'MyCoupon',
     components:{
        HeaderPage,
        FooterPage,
    },
    data(){
        return{
            nick_name:null,
            avatar:null,
            user_id:null,
            coupons:[],
            page:1,//分页查询的起始页
            promotion_code:null,
            coupon_check_type:0,
            coupon_type_options:[
                        {id:0,text:'全部'}
                    ],//默认取全部
            status:1,
            status_options:[
                        {id:1,text:'有效期内的'},
                        {id:2,text:'已使用的'},
                        {id:3,text:'已过期的'}
                    ], //默认取有效期内
            stopQuery:false,
            isAdmin:false,
        }
    },
    created(){
        this.user_profiles();
        this.get_coupon_type();
    },
    mounted(){
        const wrap=this.$refs["refScrollbar"].wrapRef;
        wrap.removeEventListener('scroll',()=>{this.scrollBarEv(wrap)});
        wrap.addEventListener('scroll',()=>{this.scrollBarEv(wrap)});
    },
    methods:{
        goto_user_center(){
            this.$router.push({ path: '/user_center/' });
        },
        //触底判断事件
        scrollBarEv(wrap) {
            this.$refs.refScrollbar.moveY = (wrap.scrollTop * 100) / wrap.clientHeight;
            this.$refs.refScrollbar.moveX = (wrap.scrollLeft * 100) / wrap.clientWidth;
            let poor = wrap.scrollHeight - wrap.clientHeight;
            if (
                poor == parseInt(wrap.scrollTop) ||
                poor == Math.ceil(wrap.scrollTop) ||
                poor == Math.floor(wrap.scrollTop)
            ) {
            console.log("已经触底了");
            if(!this.stopQuery){
                this.get_coupons(); 
            }
            }
        },

        //获取用户信息
        async user_profiles(){
            const login_token= await this.$commonFunctions.get_cookies('login_token')
            console.log("我的优惠券页面login_token："+login_token);
            
            const user_profiles= await this.$commonFunctions.get_user_profiles(login_token);
            console.log("我的优惠券页面，初始化数据："+JSON.stringify(user_profiles))

            this.nick_name=user_profiles.name;
            this.avatar=user_profiles.avatar;
            this.user_id=user_profiles.user_id;
            this.isAdmin=user_profiles.is_superuser;
            
            this.get_coupons();
        },

        //获取优惠券信息
        async get_coupons(){
            try{
                this.coupons.length=0;    //执行新查询之前清空coupons残存的数据。可以通过注释这句话的方式作为调整样式开关
            let data={
                user_id:this.user_id,
                coupon_check_type:this.coupon_check_type,   //0=全部  1=分享   2=新人
                status:this.status,     //1=有效期内的    2=使用过的    3=已过期的
                page:this.page, //当前页
                page_size:config.PAGE_SIZE,
                };
            console.log("调用前端get_coupons接口前检查数据:"+JSON.stringify(data));    
            const res=await this.$commonFunctions.get_coupons(data);
            if(res["code"]==20000){
                console.log("查询优惠券接口返回："+JSON.stringify(res));
                console.log("检查数据类型："+typeof(res["data"]));
                JSON.parse(res["data"]).forEach(element => {
                    this.coupons.push(element);
                });
                
                console.log("现在给coupons赋值，结果是:"+JSON.stringify(this.coupons)+" 完成赋值后，coupons的长度是："+this.coupons.length);
                if(this.coupons.length==config.PAGE_SIZE){
                    this.page++;
                    this.stopQuery=false;
                }else{
                    this.page=1;
                    this.stopQuery=true;
                }
            }else if(res["code"]==50001){
                this.coupons.length=0;
                this.page=1
                ElNotification({
                            message: "服务器内部错误，请联系管理员处理",
                            title: "系统消息",
                            type: "info",
                            duration: 3000,
                    }); 
            }else{
                this.coupons.length=0;
                this.page=1
                ElNotification({
                            message: res.msg,
                            title: "系统消息",
                            type: "info",
                            duration: 3000,
                    }); 
            }
            }catch(error){
                console.log(error);
                this.$router.push('/')
            }
            
        },

        //获取优惠券分类
        async get_coupon_type(){
        await axios.get("/api/get_coupon_type/",
            {withCredentials:true})
            .then(response=>
            {
                try {
                    const res=response.data;
                    console.log("get_coupon_type接口返回的数据："+JSON.stringify(res.data));
                    let x=0;
                    if(res.code==20000){
                            const coupons=JSON.parse(res.data);
                            coupons.forEach(element => {
                                console.log("代金券名称："+element.coupon_name)
                                const kvpair={"id":++x,"text":element.coupon_name};
                                this.coupon_type_options.push(kvpair);
                            });
                        }else{
                            ElNotification({
                            message: res.msg,
                            title: "系统消息",
                            type: "info",
                            duration: 3000,
                    }); 
                        }
                    } catch (error) {
                        console.log(error);
                    }
            })
        },
        //复制推广链接
        async copy_promotion_link(){
            console.log("要查询推广链接码的ID： "+this.user_id)
            this.promotion_code=await this.$commonFunctions.get_promotion_code(this.user_id);
            console.log("要粘贴的链接推广码： "+JSON.stringify(this.promotion_code))
            navigator.clipboard.writeText(config.promotion_link+'?rcode='+this.promotion_code["promotion_code"]);
            ElNotification({
                        message: "推广链接已复制到剪贴板上",
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    }); 
                },

        //选择查询条件        
        handleSelect(){
            console.log("coupon_type="+this.coupon_check_type+" status="+this.status);
            
            this.get_coupons();
        }
    },
}
</script>

<style scoped>    
.selector{
    display: inline-block;
    margin: 0 2dvw;
    font-size: inherit;
}
.filter_bar{
    height: 10%;
    width: 100%;
    background-color: #eee;
    text-align: start;
    padding: 2% 0;
}

span.filter_title{
    margin-left: 2dvw;}

.page_title{
    display: flex;
    justify-content: start;
}

.coupon_card{
    margin-top: 2dvh;
}
.coupon_row{
    margin: 5dvh 0dvw;
    display: flex;
    flex-wrap:wrap;
}
div.coupon_point{
    float: left;
    background-color: #0099FF;
    border: solid 1px #0099FF;
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
    width: 8.5dvw;
    height: 10dvh;
    font-weight:bolder ;
    color: #fff;
    font-size: larger;
    padding-top: 5dvh;
    
}

div.invalid_coupon_point{
    float: left;
    background-color: #bbb;
    border: solid 1px #bbb;
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
    width: 8.5dvw;
    height: 10dvh;
    font-weight:bolder ;
    color: #555;
    font-size: larger;
    padding-top: 5dvh;
    
}

div.coupon_name,.coupon_expiration{
    text-align:start;
    padding-left: 10dvw;
}

div.coupon_name{
    top: 0;
    bottom:50%;
    font-size:10pt;
    padding-top: 2dvh;
}
div.coupon_expiration{
    top:50%;
    bottom: 0;
    color:#6c6c6c;
    font-size:8pt;
    padding-top: 2dvh;
    
}
</style>